﻿/// <summary>
/// Classe qui permet de trie une liste d' entité
/// </summary>
/// <remarks></remarks>

using System.Collections.Generic;
using Framework.Data.Utilities;
using System;

namespace Framework.Data.Core
{

    public class EntityComparer : IComparer<IBaseEntity>
    {

        #region "Membres"
        protected string _columnName;
        #endregion
        protected DBUtils.eSortOrder _sortOrder;

        #region "Constructeur"
        /// <summary>
        /// Constructeur
        /// </summary>
        /// <param name="columnName">Nom de la colonne à comparer</param>
        /// <param name="sortOrder">L'ordre du tri</param>
        /// <remarks></remarks>
        public EntityComparer(string columnName, DBUtils.eSortOrder sortOrder)
        {
            this._columnName = columnName;
            this._sortOrder = sortOrder;
        }
        #endregion

        /// <summary>
        /// Fonction qui compare 2 entités pour le tri
        /// </summary>
        /// <param name="x">Entité 1</param>
        /// <param name="y">Entité 2</param>
        /// <returns>Integer</returns>
        /// <remarks></remarks>
        public int Compare(IBaseEntity x, IBaseEntity y)
        {
            IField column1 = x.GetField(this._columnName);
            IField column2 = y.GetField(this._columnName);
            Int32 result = 0;

            if (column1.Value == null & column2.Value != null)
            {
                result = 1;
            }
            else if (column1.Value != null & column2.Value == null)
            {
                result = -1;
            }
            else if (column1.Value == null & column2.Value == null)
            {
                result = 0;
            }
            else
            {
                //TODO: Trouver comment faire fonctionner le CompareTo
                //result = column1.Value.CompareTo(column2.Value);
            }


            if (this._sortOrder == DBUtils.eSortOrder.DESC)
            {
                if (result == 1)
                {
                    result = -1;
                }
                else if (result == -1)
                {
                    result = 1;
                }
            }
            return result;
        }
    }
}